package com.aliya.glide.builder

import android.content.Context
import android.os.SystemClock
import android.util.Log
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.cache.DiskCache
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory
import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper
import java.io.File

/**
 * InternalCacheDiskCacheCopyFactory
 *
 * @author a_liYa
 * @date 2022/2/19 18:01.
 *
 */
class InternalCacheDiskCacheCopyFactory(context: Context) :
    DiskLruCacheFactory(DiskCache.Factory.DEFAULT_DISK_CACHE_DIR, 0L) {

    private val cacheDirectory: File =
        File(context.cacheDir, DiskCache.Factory.DEFAULT_DISK_CACHE_DIR)

    private val diskCache : DiskCache? by lazy {
        if (cacheDirectory.isDirectory || cacheDirectory.mkdirs()) {
            DiskLruCacheWrapperAdapter(
                cacheDirectory,
                DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE.toLong()
            )
        } else null
    }

    override fun build(): DiskCache? {
        return diskCache

    }

    class DiskLruCacheWrapperAdapter(directory: File, maxSize: Long) :
        DiskLruCacheWrapper(directory, maxSize) {
        companion object {
            const val TAG = "磁盘缓存"
        }

        override fun put(key: Key?, writer: DiskCache.Writer?) {
            val startMs = SystemClock.uptimeMillis()
            super.put(key, writer)
            Log.e(TAG, "put 耗时: ${SystemClock.uptimeMillis() - startMs}; key: $key")
        }

        override fun get(key: Key?): File? {
            val get = super.get(key)
            Log.e(TAG, "get: $get; key: $key")
            return get
        }
    }

}